package com.kma.summer2012.client;

import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.SingleSelectionModel;
import com.kma.summer2012.shared.model.UIUser;

import java.util.List;

public class MainModule implements EntryPoint {
    public void onModuleLoad() {


        AbsolutePanel panel  = new AbsolutePanel();
        final CellTable<UIUser> positionCellTable;
        positionCellTable = new CellTable<UIUser>();    //table for user
        final UIUser positionInfo = new UIUser();   //some user info wtf

        Column<UIUser, String> nameColumn = new Column<UIUser, String>(new TextCell()) { //new column for name
            @Override
            public String getValue(UIUser object) {
                return object.getName();
            }
        };
        nameColumn.setSortable(true);                                      //column sortable oh rly?????

        Column<UIUser, String> positionColumn = new Column<UIUser, String>(new TextCell()) {   //column for position
            @Override
            public String getValue(UIUser object) {
                return object.getName();
            }
        };

        positionCellTable.addColumn(nameColumn, "Name");                          //columns added to table
        positionCellTable.addColumn(positionColumn, "Position");


        SelectionModel<UIUser> selectionModel = new SingleSelectionModel<UIUser>();

        selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
            public void onSelectionChange(SelectionChangeEvent event) {
                UIUser selectedUser = (UIUser) ((SingleSelectionModel) event.getSource()).getSelectedObject();
                positionInfo.setName(selectedUser.getName());
                }
        });

        positionCellTable.setSelectionModel(selectionModel);

        UserService.App.getInstance().getUserAllUsers(new AsyncCallback<List<UIUser>>() {
            public void onFailure(Throwable caught) {
                Window.alert(caught.getMessage());
            }

            public void onSuccess(List<UIUser> result) {
                ListDataProvider<UIUser> data = new ListDataProvider<UIUser>(result);
                data.addDataDisplay(positionCellTable);
            }
        });


        panel.add(positionCellTable);
        //panel.add(positionInfo);

        RootPanel.get("main").add(panel);
    }
}
